package com.bjpowernode.web.service;

import com.alibaba.fastjson.JSONObject;
import com.bjpowernode.contacts.RedisKey;
import com.bjpowernode.web.config.CXSmsConfig;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: panDeng_Zhu
 * @time: 2022/11/2 8:57
 */
@Service
public class SmsService {

    @Resource
    private CXSmsConfig cxSmsConfig;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 完整的处理短信业务
     *
     * @param phone
     * @return
     */
    public boolean handlerSendSmsCode(String phone) {

        //使用apache-common-lang3中的随机数类
        String randomCode = RandomStringUtils.randomNumeric(4);
        //调用发送短信的方法
        boolean isSend = invokeCXSmsApi(phone, randomCode);
        if (isSend){
            storeSmsCodeToRedis(phone,randomCode);
        }
        return isSend;
    }

    //验证smsCode
    public boolean checkSmsCode (String phone,String smsCode){
        boolean result =false;//验证码不正确
        String key = RedisKey.SMS_CODE_REGISTER +phone;
        if (stringRedisTemplate.hasKey(key)){
            //从redis中获取数据
            String querySmcCode = stringRedisTemplate.opsForValue().get(key);
            if (smsCode.equals(querySmcCode)){
                result=true;
            }
        }
        return result;
    }

    //存放验证码
    private void storeSmsCodeToRedis(String phone, String smsCode) {
        String key = RedisKey.SMS_CODE_REGISTER + phone;
        stringRedisTemplate.opsForValue().set(key, smsCode, 3, TimeUnit.MINUTES);
    }

    //发送注册短信
    private boolean invokeCXSmsApi(String phone, String randomCode) {
        boolean isSend = false;
        //使用HttpClient
        String url = cxSmsConfig.getUrl();
        String appkey = cxSmsConfig.getAppkey();
        //创建短信文本
        String content = String.format(cxSmsConfig.getContent(), randomCode);
        Map<String, String> params = new HashMap<>();
        params.put("mobile", phone);
        params.put("content", content);
        params.put("appkey", appkey);

        try {
            String json = "{\n" +
                    "    \"code\": \"10000\",\n" +
                    "    \"charge\": false,\n" +
                    "    \"remain\": 1305,\n" +
                    "    \"msg\": \"查询成功\",\n" +
                    "    \"result\": {\n" +
                    "        \"ReturnStatus\": \"Success\",\n" +
                    "        \"Message\": \"ok\",\n" +
                    "        \"RemainPoint\": 420842,\n" +
                    "        \"TaskID\": 18424321,\n" +
                    "        \"SuccessCounts\": 1\n" +
                    "    }\n" +
                    "}";
            //解析json，使用fastjson
            if (StringUtils.isNotBlank(json)) {
                //读取json
                JSONObject jsonObject = JSONObject.parseObject(json);
                //调用第三方接口成功
                if ("10000".equals(jsonObject.getString("code"))) {
                    //获取发送短信的结果值
                    String returnSuccess = jsonObject.getJSONObject("result").getString("ReturnStatus");
                    if ("Success".equals(returnSuccess)) {
                        //短信发送成功
                        isSend = true;
                    }
                }
            }
        } catch (Exception e) {
            isSend = false;
            e.printStackTrace();
        }
        return isSend;
    }
}
